package cn.burnit.utils;


import javax.swing.table.AbstractTableModel;
import java.sql.*;

/**
 * 图书表格数据
 */
public class BookTableModel extends AbstractTableModel {

    private int rowCount;//总行
    private int columnCount;//总列
    private ResultSet result;//返回结构集
    private PreparedStatement ps;

    public BookTableModel() {
        ConnectUtils.getDriver();
        Connection connection=null;

        try {
            connection=ConnectUtils.getConnection();
            String selSql="select * from book";
            ps = connection.prepareStatement(selSql);
            result = ps.executeQuery();
            //将光标定位在最后一行
            result.last();
            //获取最大行数
            rowCount = result.getRow();
            //通过结果集对象来获取数据库的字段
            ResultSetMetaData data = result.getMetaData();
            //获取列数
            columnCount = data.getColumnCount();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    // 返回一共有多少行
    @Override
    public int getRowCount() {
        return rowCount;
    }

    // 返回一共有多少列
    @Override
    public int getColumnCount() {
        return columnCount;
    }


    // 每一个单元格里的值
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Object value = null;
        try {
            result.absolute(rowIndex+1);
            value=result.getString(columnIndex+1);
        }catch (Exception e){
            e.printStackTrace();
        }
        return value;
    }


}
